package Domain.forumProtcol;

import com.thoughtworks.xstream.XStream;

import Domain.forumManager.ForumController;
import Domain.stompProtocol.ForumFrame;
import Domain.stompProtocol.StompClient;
import Domain.stompProtocol.StompFrame;

public abstract class ProtocolHelper
{

	
	/** The queue prefix. */
	protected String queuePrefix = "";
	protected XStream xstream=new XStream();
	/** The _stomp client. */
	protected StompClient _stompClient;
	protected ForumController forumController;
	protected final char DELIMITER=';';  //will separate the filed in the message at the protocol
	protected ForumFrame forumfrm;
	
	public String getNameOfForum(String str)
	{
		try 
		{
			int index = str.indexOf(DELIMITER)+1;
			int indexend = str.indexOf(DELIMITER, index);
			if(indexend == -1)
				indexend = str.length();
			String tmp = str.substring(index,indexend).trim();
			return tmp;
		} 
		catch (RuntimeException e) 
		{
		} 
		return null;
	}


	public String getNameOfThread (String str)
	{
		try 
		{
			int index = str.indexOf(DELIMITER)+1;
			String tmp = str.substring(index).trim();
			index = tmp.indexOf(DELIMITER)+1;
			int indexend =tmp.indexOf(DELIMITER, index);
			if (indexend == -1)
				indexend = tmp.length();
			tmp = tmp.substring(index,indexend).trim();
			return tmp;
		} 
		catch (RuntimeException e) 
		{
		}
		return null;
	}
	
	public String getTitleOfMessage(String str)
	{
		int i=str.lastIndexOf(DELIMITER);
		String ans=str.substring(0, i);
		i=ans.lastIndexOf(DELIMITER);
		return ans.substring(i+1).trim();
	}
	public String getContentsOfMessage(String str)
	{
		
		int i=str.lastIndexOf(DELIMITER);
		return str.substring(i+1).trim();
		
	}

	
	protected String sendSecessMessage(String nameOfUser)
	{
		forumfrm.setSeccessOporation();
		return this.sendPlayerMsg(nameOfUser,forumfrm);
	}
	
	protected String InvalidMessage(String nameOfUser)
	{
		System.out.println(" inviled format of message\n");
		forumfrm.setErr(forumfrm.UNKOWNERR);
		return this.sendPlayerMsg(nameOfUser, forumfrm);
	}


	public ForumFrame getForumfrm()
	{
		return forumfrm;
	}
	

	/**
	 * Send player msg.
	 *
	 * @param user the user that send the message
	 * @param msg the msg
	 */
	protected String sendPlayerMsg(String user,String msg)
	{
		
		this._stompClient.sendStompFrame(StompFrame.createSendFrame("fserver",this.queuePrefix + user , msg));
		return msg;
	}
	/**
	 * send the user the frame as xml
	 * @param user the user we want to send the frame
	 * @param f the forumframe to be sent
	 * @return the message that has sent
	 */
	protected String sendPlayerMsg(String user,ForumFrame f)
	{
		this.xstream.alias("ForumFrame", ForumFrame.class);
		String xml=this.xstream.toXML(f);
		return this.sendPlayerMsg(user, xml);
		
	}
	
	
	
	
}
